<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
          integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

    <style>
        .breadcrumb {
            padding: 15px 15px;
            background-color: transparent;
            margin-bottom: 0px;
            display: inline-block;
        }

        .pull-right {
            padding-top: 7px;
        }

        .inline-block {
            display: inline-block;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-default">
    <div class="container">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">书本商城</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ol class="breadcrumb">
                <li><a href="#">首页</a></li>
                <li class="active">购物车</li>
            </ol>
            <div class="btn-group pull-right" role="group" aria-label="...">
                <button type="button" class="btn btn-danger">修改密码</button>
                <button type="button" class="btn btn-danger">注销</button>
            </div>
        </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
</nav>
<div id="app" class="container">
    <div class="panel panel-default">
        <div class="panel-heading">
            <form class="form-inline inline-block">
                <div class="form-group">
                    <input type="text" class="form-control input-sm" v-model.trim="searchArgs.name" placeholder="书本">
                </div>
                <div class="form-group">
                    <input type="number" class="form-control input-sm" v-model.number="searchArgs.minPrice"
                           placeholder="最低价">
                </div>
                <div class="form-group">
                    <input type="number" class="form-control input-sm" v-model.number="searchArgs.maxPrice"
                           placeholder="最高价">
                </div>
                <button type="button" class="btn btn-default btn-sm" @click="search">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                </button>
            </form>
            <div class="inline-block" style="float: right;">
                <button type="button" class="btn btn-success">添加</button>
                <button type="button" class="btn btn-success" @click="delBatch">批量删除</button>
            </div>
        </div>
        <div class="panel-body">
            <my-table title-class="text-center" :titles="titles">
                <template>
                    <tr v-for="(item, index) in pageData" :key="item.id">
                        <td><input type="checkbox" name="cb_select" v-model="batchIds" v-bind:value="item.id"></td>
                        <td>{{item.id}}</td>
                        <td v-text="item.name"></td>
                        <td>{{item.createDate | zhDate}}</td>
                        <td>{{item.price | zhPrice}}</td>
                        <td>
                            <button @click="mouse(index)">-</button>
                            {{item.count}}
                            <button @click="add(index)">+</button>
                        </td>
                        <td>
                            <button>编辑</button>
                            <button @click="del(index)">删除</button>
                        </td>
                    </tr>
                </template>
            </my-table>
            <pagination :pager="pager"></pagination>
        </div>
        <div class="panel-footer">{{totalPrice | zhPrice}}</div>
    </div>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<!--bootstrap的JS是需要Jquery的支持-->
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>
<script src="../js/vue.js"></script>
<script src="../js/mock.js"></script>
<script src="../js/util/moment.js"></script>
<script src="../js/PagerHelper.js"></script>
<script>
    //通过mock产生100条记录

    let Random = Mock.Random;
    Random.extend({
        getName: function () {
            let array = ["JAVA", "JAVASCRIPT", "HTML", "CSS", "MYSQL", "ORACLE", "JQUERY", "SERVLET", "JSP", "SPRING", "SPRING MVC"];
            return this.pick(array);
        }
    })
    let data = Mock.mock({
        "books|100": [{
            "id|+1": 1,
            "createDate": "@date('2021-MM-dd')",
            "name": "@getName()" + " 从入门到放弃",
            "price": "@integer(30, 100)",
            "count": "@integer(1, 10)"
        }]
    });

    //全局组件
    Vue.component("pagination", {
        data() {
            return {}
        },
        props: ["pager"],
        template: `
          <nav class="row">
          <div id="page_total" class="col-md-2 col-sm-2" style="line-height: 79.6px;">共有{{ pager.count }}条记录
          </div>
          <div class="col-md-8 col-sm-8 text-center">
            <ul class="pagination">
              <!--                        <li v-for="i in pager.total" :class="{active: pager.pageNum == i}"><a href="#">{{i}}</a></li>-->
              <li @click="pager.pageNum = 1" :style="{display: pager.pageNum == 1 ? 'none' : 'inline'}"><a
                  href="#">首页</a></li>
              <li @click="pager.pageNum > 1 ? pager.pageNum-- : ''"
                  :style="{display: pager.pageNum == 1 ? 'none' : 'inline'}"><a href="#">上一页</a></li>
              <li v-for="i in pager.total" @click="pager.pageNum = i"
                  :class="[pager.pageNum == i ? 'active' : '']"><a href="#">{{ i }}</a></li>
              <li @click="pager.pageNum++"
                  :style="{display: pager.pageNum == pager.total ? 'none' : 'inline'}"><a href="#">下一页</a>
              </li>
              <li @click="pager.pageNum = pager.total"
                  :style="{display: pager.pageNum == pager.total ? 'none' : 'inline'}"><a href="#">尾页</a></li>
            </ul>
          </div>
          <div class="col-md-2 col-sm-2" style="margin: 20px 0">
            <select class="form-control" id="page_select">
              <!--                        <option>2</option>-->
              <!--                        <option>5</option>-->
              <!--                        <option>10</option>-->
              <option v-for="item in pager.options">{{ item }}</option>
            </select>
          </div>
          </nav>
        `
    });

    Vue.component("my-table", {
        data() {
            return {};
        },
        props: {titles: Array, "titleClass": String},
        template: `
          <table class="table table-hover table-bordered">
          <thead>
          <tr>
            <th :class="titleClass" v-for="item in titles" v-html="item"></th>
          </tr>
          </thead>
          <tbody>
          <slot>
          </slot>
          </tbody>
          </table>
        `
    })

    let app = new Vue({
        el: "#app",
        data: {
            // books: [
            //     {id: 1, name: 'Java从入门到放弃', price: 80, tdate: '2020-07-01', count: 1},
            //     {id: 2, name: 'Vue从入门到放弃', price: 90, tdate: '2020-07-02', count: 1},
            //     {id: 3, name: 'Mysql从入门到放弃', price: 100.01, tdate: '2020-07-03', count: 1},
            //     {id: 4, name: '啥都从入门到放弃', price: 70.00, tdate: '2020-07-04', count: 1},
            // ],
            books: data.books,
            pager: new PagerHelper(""),
            batchIds: [],
            searchArgs: {},
            list: data.books,
            titles: ["<input name='cb_select_all' type='checkbox'>", "序号", "书名", "日期", "单价", "数量", "操作"]
        },
        created() {
            this.pager.setCount(this.list.length);
            console.log(this.pager);
        },
        computed: {
            // 计算属性的 getter
            // reversedMessage: function () {
            //     // `this` 指向 vm 实例
            //     return this.message.split('').reverse().join('')
            // },
            // pageData() {
            //     console.log("pageData");
            //     return this.books.filter((value, index) => index >= (this.pager.pageNum - 1) * this.pager.pageSize && index < this.pager.pageNum * this.pager.pageSize)
            // }
            totalPrice() {
                return this.pageData.reduce((pre, next) => pre += next.price * next.count, 0);
            },
            pageData: {
                // getter
                get: function () {
                    return this.list.filter((value, index) => index >= (this.pager.pageNum - 1) * this.pager.pageSize && index < this.pager.pageNum * this.pager.pageSize)
                },
                // setter
                set: function (newValue) {
                    console.log(newValue);
                    this.list = newValue;
                    this.pager.setCount(this.list.length);
                }
            }
            // pager() {
            //     let ph = new PagerHelper("");
            //     ph.setCount(this.list.length);
            //     console.log(ph);
            //     return ph;
            // }
        },
        methods: {
            mouse(index) {
                if (this.books[index].count > 0) {
                    this.books[index].count--;
                }
            },
            add(index) {
                this.books[index].count++;
            },
            del(index) {
                this.books.splice(index, 1);
            },
            delBatch() {
                let cfm = confirm(`确定删除选中${this.batchIds}的记录?`);
                if (cfm) {
                    this.batchIds.forEach(id => this.books.splice(this.books.findIndex(value => id == value.id), 1));
                }
            },
            // pageData(searchResult) {
            //     console.log("pageData");
            //     if (searchResult) {
            //         return searchResult;
            //     }
            //     return this.books.filter((value, index) => index >= (this.pager.pageNum - 1) * this.pager.pageSize && index < this.pager.pageNum * this.pager.pageSize)
            // },
            search() {
                let filterBooks = this.books;
                if (this.searchArgs.name) {
                    filterBooks = filterBooks.filter(value => value.name.toLowerCase().indexOf(this.searchArgs.name.trim().toLowerCase()) != -1);
                }
                if (this.searchArgs.minPrice) {
                    filterBooks = filterBooks.filter(value => value.price >= this.searchArgs.minPrice);
                }
                if (this.searchArgs.maxPrice) {
                    filterBooks = filterBooks.filter(value => value.price <= this.searchArgs.maxPrice);
                }
                this.pageData = filterBooks;
            }
        },
        filters: {
            zhPrice(value) {
                return "￥" + value;
            },
            zhDate(value) {
                console.log(value);
                return moment(value).format("YYYY年MM月DD日");
            }
        }
    });

</script>
</body>
</html>